package middleware

import (
	"encoding/json"
	"gitee.com/yangguoliang001/go-gin-vue3/BO"
	"gitee.com/yangguoliang001/go-gin-vue3/config"
	"gitee.com/yangguoliang001/go-gin-vue3/pkg/response"
	"gitee.com/yangguoliang001/go-gin-vue3/util/code"
	"github.com/gin-gonic/gin"
	"regexp"
)

func (i interceptor) RGBAMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		signToken := c.GetHeader(config.HeaderLoginToken)
		tokenStr := signToken[7:] // token

		if b := i.cache.Exists(config.RedisKeyPrefixLoginUser + tokenStr + ":actions"); b.Val() == 0 {
			response.Fail(c, code.CacheNotExist, code.Text(code.CacheNotExist), gin.H{"real": "当前账号未配置rbac权限"})
			c.Abort()
		}

		actionStr := i.cache.Get(config.RedisKeyPrefixLoginUser + tokenStr + ":actions")
		var actionData []BO.MyMenuActionListBO
		_ = json.Unmarshal([]byte(actionStr.Val()), &actionData)
		isAuth := false
		//fmt.Println("******", c.Request.Method, c.Request.URL, c.Request.URL.Path, isAuth)
		for _, datum := range actionData {
			matched, _ := regexp.MatchString(datum.Api, c.Request.URL.Path)
			if matched && c.Request.Method == datum.Method {
				isAuth = true
			}
		}
		if !isAuth {
			response.Fail(c, code.RBACError, code.Text(code.RBACError), gin.H{"realErr": "未进行 RBAC 授权"})
			c.Abort()
		}
		c.Next()
	}
}
